package org.university.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.university.entity.Major;
import org.university.repository.MajorRepository;
import org.university.service.MajorService;

@Service
public class MajorServiceImpl extends GenericServiceImpl<Major, Integer> implements MajorService {

    private static final Logger logger = LoggerFactory.getLogger(MajorServiceImpl.class);
    private final MajorRepository majorRepository;

    public MajorServiceImpl(MajorRepository repository, MajorRepository majorRepository) {
        super(repository);
        this.majorRepository = majorRepository;
    }

    @Override
    public Major save(Major major) {
        Integer id = major.getMajorId();
        logger.info("保存专业ID: {}", id);
        if (id != null && majorRepository.existsById(id)) {
            throw new IllegalArgumentException("专业ID已存在: " + id);
        }
        return majorRepository.save(major);
    }

    @Override
    public Page<Major> findAll(Pageable pageable) {
        logger.info("查询所有专业: 分页信息={}", pageable);
        return majorRepository.findByDeletedFalse(pageable);
    }

    @Override
    public Page<Major> findAll() {
        logger.info("查询所有专业（无分页）");
        return majorRepository.findByDeletedFalse(Pageable.unpaged());
    }

    @Override
    public void deleteById(Integer id) {
        logger.info("删除专业ID: {}", id);
        majorRepository.findById(id).ifPresent(major -> {
            major.setDeleted(1);
            majorRepository.save(major);
        });
    }
}